package com.alipay.sofa.award.biz.service.impl;

import com.alipay.sofa.award.biz.service.facade.UserVisitRecordFacade;
import com.alipay.sofa.award.common.dal.dao.UserVisitRecordMapper;
import com.alipay.sofa.award.common.dal.dataobject.UserInfo;
import com.alipay.sofa.award.common.dal.dataobject.UserVisitRecord;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.TransactionStatus;
import org.springframework.transaction.support.TransactionCallback;
import org.springframework.transaction.support.TransactionTemplate;

import java.util.Date;

/**
 * UserVisitRecordImpl
 *
 * @author yangguanchao
 * @since 2018/09/13
 */
public class UserVisitRecordImpl implements UserVisitRecordFacade {

    private static final Logger   logger = LoggerFactory.getLogger(UserVisitRecordImpl.class);

    @Autowired
    private TransactionTemplate   transactionTemplate;

    @Autowired
    private UserVisitRecordMapper userVisitRecordMapper;

    @Override
    public boolean userVisitedOnActivityTime(boolean isStored, UserInfo userInfo,
                                             String activityTime) {

        return this.transactionTemplate.execute(new TransactionCallback<Boolean>() {
            @Override
            public Boolean doInTransaction(TransactionStatus transactionStatus) {
                try {
                    UserVisitRecord userVisitRecordSelected = userVisitRecordMapper
                        .selectByUserIdAndActivityTime(userInfo.getUserId(), activityTime);
                    if (userVisitRecordSelected == null) {
                        if (isStored) {
                            UserVisitRecord userVisitRecord = new UserVisitRecord();
                            userVisitRecord.setActivityTime(activityTime);
                            userVisitRecord.setUserId(userInfo.getUserId());
                            userVisitRecord.setNickName(userInfo.getNickName());
                            userVisitRecord.setVisitTimes(1);
                            userVisitRecord.setModifyTime(new Date());
                            userVisitRecordMapper.insert(userVisitRecord);
                        }
                        return false;
                    } else {
                        if (isStored) {
                            userVisitRecordMapper.addVisitTimesOnceByUserIdAndActivityTime(
                                userInfo.getUserId(), activityTime);
                        }
                        return true;
                    }
                } catch (Exception exception) {
                    transactionStatus.setRollbackOnly();
                    logger.error("userHasVisitedOnActivityTime Error!", exception);
                    //if exception then allow try win the lottery
                    return false;
                }
            }
        });
    }
}
